<template>
  <view class="tab-selector">
    <scroll-view class="tab-scroll" scroll-x="true" :scroll-left="scrollLeft">
      <view class="tab-list">
        <view
          v-for="(item, index) in tabs"
          :key="index"
          class="tab-item"
          :class="{ active: activeIndex === index }"
          @click="changeTab(index)"
        >
          <text class="tab-text">{{ item.name }}</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from "vue";

// 定义组件属性
const props = defineProps({
  tabs: {
    type: Array,
    default: () => [],
  },
  activeTab: {
    type: Number,
    default: 0,
  },
});

// 定义事件
const emit = defineEmits(["update:activeTab", "change"]);

// 当前激活的标签索引
const activeIndex = ref(props.activeTab);

// 处理标签切换
const changeTab = (index) => {
  activeIndex.value = index;
  emit("update:activeTab", index);
  emit("change", props.tabs[index], index);
};

// 计算滚动位置
const scrollLeft = ref(0);

// 监听activeTab变化
watch(
  () => props.activeTab,
  (newVal) => {
    activeIndex.value = newVal;
  }
);

// 监听activeIndex变化计算滚动位置
watch(activeIndex, (newVal) => {
  // 简单的滚动逻辑，实际项目中可能需要根据元素位置计算
  scrollLeft.value = newVal * 80; // 假设每个tab宽度为80
});
</script>

<style>
.tab-selector {
  width: 100%;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  box-sizing: border-box;
}

.tab-scroll {
  white-space: nowrap;
  width: 100%;
  overflow-x: auto;
}

.tab-list {
  display: flex;
  height: 80rpx;
  flex-wrap: nowrap;
}

.tab-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  padding: 0 30rpx;
  position: relative;
  flex-shrink: 0;
}

.tab-text {
  font-size: 28rpx;
  color: #999999;
}

.tab-item.active .tab-text {
  color: #4361ee;
  font-weight: 500;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #4361ee;
  border-radius: 2rpx;
}
</style>
